//
//  TangKaController.m
//  民族文化宫
//
//  Created by WANG CUNRUI on 14-6-5.
//  Copyright (c) 2014年 WANG CUNRUI. All rights reserved.
//

#import "TangKaController.h"
#import "MZAppDelegate.h"
#import "ASIHTTPRequest.h"
static NSString *ID = @"MyCell";
int count;
@interface TangKaController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic)NSInteger countp;
@property (strong, nonatomic) NSMutableArray *arrayM1;
@property (strong, nonatomic) NSMutableArray *currentdata;
@property (strong, nonatomic) NSData *data;
@property (strong,nonatomic)NSString *imagePath;
@end

@implementation TangKaController

-(void)cache
{
//    [super viewWillAppear:animated];
    
    //如果NSUserDefaults中没有ProductLastUpdate，则设置其初始值。
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"TangkaLastUpdate"]) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"TangkaLastUpdate"];
    }
    
    //获取全局变量
    MZAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    NSURL *productURL = [NSURL URLWithString:@"http://210.30.0.167:6162/mzserver/Jingpins/findJingpinsByLeibie?leibie=%E5%94%90%E5%8D%A1%E8%89%BA%E6%9C%AF&p=1"];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:productURL];
    request.delegate = self;
    [request setDownloadCache:appDelegate.myCache];
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    
    //判断刷新时间间隔
    if ([MZTool IsNeedUpdate:@"TangkaLastUpdate"]) {
        
        //只有在网络状态连通，且满足刷新时间间隔的情况下，request才不读缓存中的内容。
        //如果目前网络状态连通
        if ([MZTool IsEnable3G] == YES || [MZTool IsEnableWIFI] == YES) {
            [request setCachePolicy:ASIDoNotReadFromCacheCachePolicy];
            NSLog(@"从服务器读数据");
        }else{
            UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载数据失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
            [result show];
            
        }
        [request startAsynchronous];
        NSLog(@"主页下载中");
    }
    else
    {
        [request startAsynchronous];
    }

}


- (void)loadView
{
    [self cache];
    self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor colorWithRed:0.9373 green:0.9216 blue:0.9059 alpha:1.0];
    // 1. tableView
    CGRect frame = self.view.bounds;
    self.title = @"唐卡艺术";
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height-28) style:normal];
    // 1) 数据源
    [tableView setDataSource:self];
    // 2) 代理
    [tableView setDelegate:self];
    // 3) 设置表格高度
    [tableView setRowHeight:100];
    // 4) 设置分隔线
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    tableView.separatorInset = UIEdgeInsetsMake(0, 3, 0, 11);
    [self.view addSubview:tableView];
    self.tableView = tableView;
//    [self loadJson];
    [self setupRefresh];
    [self Reshing];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.tableView registerClass:[TKCellTableViewCell class] forCellReuseIdentifier:ID];
    // Do any additional setup after loading the view.
}

-(void)Reshing
{
    NSURL *urls = [NSURL URLWithString:@"http://210.30.0.167:6162/mzserver/Jingpins/findJingpinsByLeibie?leibie=%E5%94%90%E5%8D%A1%E8%89%BA%E6%9C%AF&p=1"];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:urls];
    //request.delegate = self;
    
    [request startSynchronous];
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        _currentdata = [[request responseData]JSONValue] ;
        [self.tableView reloadData];
    }
    else{
//        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载数据失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
//        [result show];
    }
    [self.tableView headerEndRefreshing];
    count = 2;
    _countp = 2;
}

- (void)startRefresh:(int)count
{
    NSString *str = [NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/Jingpins/findJingpinsByLeibie?leibie=唐卡艺术&p=%ld",(long)count];
    NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
    NSURL *url = [NSURL URLWithString:encodedString];
    NSLog(@"url2 = %@",url);
    // 2. 建立NSURLRequest
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    //request.delegate = self;
    [request startSynchronous];
    //    _currentdata = [NSMutableArray array];
    NSLog(@"current2 = %lu",(unsigned long)_currentdata.count);
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        NSData *data = [request responseData];
        NSLog(@"data2=%@",data.JSONValue );
        NSMutableArray *ARRAY = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *currentarray = [[NSMutableArray alloc]init];
        [currentarray addObjectsFromArray:_currentdata];
        [currentarray addObjectsFromArray:ARRAY];
        _currentdata = currentarray;
        if (![ARRAY  isEqual: @[]]) {
            NSLog(@"success");
            
            count = count + 1;
            
            NSLog(@"count11 = %ld",(long)count);
            
        }
        _countp = count;
        NSLog(@"array = %@",ARRAY);
        NSLog(@"current2.1 = %lu",(unsigned long)_currentdata.count);
        //        [self.dataList addObjectsFromArray:_currentdata];
        NSLog(@"datalist2 = %@",self.dataList);
        // 刷新表格
        [self.tableView reloadData];
    }else{
        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载数据失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
        [result show];
    }
}


- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    //    [self.tableView headerBeginRefreshing];
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

-(void)headerRereshing
{
    NSURL *urls = [NSURL URLWithString:@"http://210.30.0.167:6162/mzserver/Jingpins/findJingpinsByLeibie?leibie=%E5%94%90%E5%8D%A1%E8%89%BA%E6%9C%AF&p=1"];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:urls];
    //request.delegate = self;
    // 给数据列表赋值
    // 2.1.5秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [request startSynchronous];
        NSLog(@"下载产品数据中");
        NSError *error = [request error];
        if (!error) {
            _currentdata = [[request responseData]JSONValue] ;
            [self.tableView reloadData];
        }
        else{
            UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载数据失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
            [result show];
        }
        
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
    
    
}

- (void)footerRereshing
{
    count = _countp;
    
    if (flag == NO) {
        
        NSLog(@"countp = %ld",(long)_countp);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self startRefresh:count];
            
            // 刷新表格
            [self.tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        });
        NSLog(@"%@2222",_arrayM1);
        _countp = _countp + 1;
        
        
    }else
    {
        // 2.2秒后刷新表格UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        });
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _currentdata.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1. 使用可重用标示符查询可重用单元格
    MJCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 设置单元格内容
    NSDictionary *dic = _currentdata[indexPath.row];
    cell.textLabel.text = [dic objectForKey:@"JingPin_name"];
    cell.detailLabel.text = [dic objectForKey:@"JingPin_shuoming_C"];
    NSString *pic = [dic objectForKey:@"JingPin_pic"];
    
    if (cell.imageView == nil) {
        // 使用默认图像占位，既能够保证有图像，又能够保证有地方！
        UIImage *image = [UIImage imageNamed:@"user_default.png"];
        [cell.imageView setImage:image];
        
        
        
    } else {
        UIImage *image = [UIImage imageNamed:@"user_default.png"];
        [cell.imageView setImage:image];
        NSRange foundObj = [pic rangeOfString :@";" options:NSCaseInsensitiveSearch];
        if(foundObj.length>0)
        {
            NSRange range = [pic rangeOfString:@";"];
            NSString *b = [pic substringToIndex:range.location];
            
            NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", b];
            
            _imagePath = imagePath;
        }else
        {
            NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", pic];
            
            _imagePath = imagePath;
        }
        //检测地址是否含有两张图片，有则取分号前一张
        [cell.imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imagePath]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    }
    
    
    return cell;
}


- (void)handlerJSONData:(NSData *)data
{
    
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    
    NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docs[0]stringByAppendingPathComponent:@"json8.plist"];
    [array writeToFile:path atomically:YES];
    
    
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        Data *video = [[Data alloc]init];
        
        
        [video setValuesForKeysWithDictionary:dict];
        
        [arrayM addObject:video];
    }
    
    self.dataList = arrayM;
    
    // 刷新表格
    [self.tableView reloadData];
    _countp = 2;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _TKDetailViewController = [[TKDetailViewController alloc] init];
    //    Data *v = self.dataList[indexPath.row];
    NSDictionary *dic = _currentdata[indexPath.row];
    _TKDetailViewController.leibie = [dic objectForKey:@"JingPin_leibie"];
    _TKDetailViewController.minzu = [dic objectForKey:@"JingPin_minzu"];;
    _TKDetailViewController.pic = [dic objectForKey:@"JingPin_pic"];;
    _TKDetailViewController.time = [dic objectForKey:@"JingPin_shidai"];;
    _TKDetailViewController.content_c = [dic objectForKey:@"JingPin_shuoming_C"];;
    _TKDetailViewController.content_e = [dic objectForKey:@"JingPin_shuoming_E"];;
    _TKDetailViewController.chicun = [dic objectForKey:@"JingPin_chichu"];;
    _TKDetailViewController.diqu = [dic objectForKey:@"JingPin_diqu"];;
    _TKDetailViewController.zhidi = [dic objectForKey:@"JingPin_dizhi"];;
    _TKDetailViewController.name = [dic objectForKey:@"JingPin_name"];;
    
    
    [self.navigationController pushViewController:_TKDetailViewController animated:YES];
    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    //    NSData *data = [request responseData];
    _currentdata = [[request responseData] JSONValue];
    
    [self.tableView reloadData];
    
    //判断数据来源并决定是否刷新数据更新时间
    if ([request didUseCachedResponse] == NO) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"TangkaLastUpdate"];
        NSLog(@"数据来自服务器,TK下载成功");
    }
    else
    {
        NSLog(@"数据来自缓存,TK下载成功");
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
    [result show];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
